package com.gz.gzmybatis.sqlsession;

import com.gz.gzmybatis.config.Function;
import com.gz.gzmybatis.config.MapperBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class GzMapperProxy implements InvocationHandler {
    private GzSqlSession gzSqlSession;
    private String mapperFile;
    private GzConfiguration gzConfiguration;

    public GzMapperProxy(GzConfiguration gzConfiguration,
                         GzSqlSession gzSqlSession,
                         Class clazz) {
        this.gzSqlSession = gzSqlSession;
        this.gzConfiguration = gzConfiguration;
        this.mapperFile = clazz.getSimpleName() + ".xml";
    }

    /**
     *当执行Mapper接口的代理对象时，会执行该方法
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        MapperBean mapperBean = gzConfiguration.readMapper(this.mapperFile);
        //因为Mapper接口有很多，所以要判断是不是对应的接口
        if (!method.getDeclaringClass().getName().equals(mapperBean.getInterfaceName())) {
            return null;
        }
        List<Function> functions = mapperBean.getFunctions();
        if (functions != null && functions.size() != 0) {
            for (Function function : functions) {
                //如果要执行的方法和function.getFuncName()对应
                //那么取出相应信息 sql
                if (method.getName().equals(function.getFuncName())){//getMonsterById()
                    //如果是select，就执行selectOne
                    //注意这是简化版，select肯定还代表其他方法，这里只用selectOne
                    if ("select".equalsIgnoreCase(function.getSqlType())){
                        return gzSqlSession.selectOne(function.getSql(), String.valueOf(args[0]));
                    }
                }
            }
        }
        return null;
    }
}
